﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Logging;
using VAdvantage.Grids;
using VAdvantage.Classes;
using VAdvantage.Utility;
using System.Windows.Data;
using VAdvantage.DataBase;
using VAdvantage.Model;

namespace VAdvantage.Controls
{
    public partial class VPAttribute : UserControl, IControl, IEditingControl
    {

        #region "Declaration"

        /**	Data Value				*/
        private Object _value;
        /** The Attribute Instance	*/
        private MPAttributeLookup _mPAttribute;

        private bool _readOnly;
        private bool _mandatory;
        private int _windowNo;
        private static int _C_BPartner_ID;

        /**	Calling Window Info				*/
        private int _AD_Column_ID = 0;
        /**	No Instance Key					*/
        private static int NO_INSTANCE = 0;
        /**	Logger			*/
        private static VLogger log = VLogger.GetVLogger(typeof(VPAttribute).FullName);
        // private ToolStripMenuItem mnuItem = null;

        /** Grid Field				*/
        private GridField _field = null;

        private int _displayType = DisplayType.PAttribute;

        private string _colName = "M_AttributeSetInstance_ID";

        private bool _focus;
        private Binding binding;

        #endregion

        #region Propeties

        /// <summary>
        /// Text of Control
        /// </summary>
        public string Text
        {
            get { return this.txtAttribute.Text; }
            set { this.txtAttribute.Text = value; }
        }

        #endregion

        #region Property

        public static readonly DependencyProperty TextValueProperty =
         DependencyProperty.Register("TextValue", typeof(int), typeof(VAdvantage.Controls.VPAttribute), new PropertyMetadata((o, e) =>
         {
             ((VPAttribute)o).SetTextValue((int)e.NewValue);
         }));


        public int TextValue
        {
            get
            {
                return ((int)GetValue(VPAttribute.TextValueProperty));
            }
            set
            {
                SetValue(VPAttribute.TextValueProperty, value);
            }
        }

        void SetTextValue(int newVal)
        {
            //TextValue = newVal;
            int? id = null;
            if (TextValue == 0)
            {
                id = null;
            }
            else
            {
                id = TextValue;
            }
            SetValue(id);
        }


        #endregion
        public VPAttribute()
        {
            InitializeComponent();
            btnAttribute.Content = new Image() { Source = Utility.Envs.LoadImageSource("PAttribute10.png") };
        }


        public VPAttribute(string colName, bool mandatory, bool isReadOnly, bool isUpdateable,
           int windowNo, MPAttributeLookup lookup)
            : this()
        {
            // InitializeComponent();
            //this.Name = colName;
            _colName = colName;
            _windowNo = windowNo;
            _mPAttribute = lookup;
            _C_BPartner_ID = Envs.GetCtx().GetContextAsInt(windowNo, "C_BPartner_ID");
            txtAttribute.IsReadOnly = true;
            SetIsMandatory(mandatory);
            if (isReadOnly || !isUpdateable)
                SetReadOnly(true);
            else
                SetReadOnly(false);
            //if (!DataBase.GlobalVariable.IsVisualEditor)
            //{
            this.btnAttribute.Click += new RoutedEventHandler(btnAttribute_Click);
            this.txtAttribute.TextChanged += new TextChangedEventHandler(txtAttribute_TextChanged);
            // SetPopup();
            //}
            //else
            //{
            //    this.txtAttribute.MouseDown += new MouseEventHandler(txtAttribute_MouseDown);
            //    this.txtAttribute.MouseMove += new MouseEventHandler(txtAttribute_MouseMove);
            //    this.txtAttribute.MouseUp += new MouseEventHandler(txtAttribute_MouseUp);
            //    this.txtAttribute.MouseEnter += new EventHandler(txtAttribute_MouseEnter);

            //}
            //this.Width = 300;
            // this.DataBindings.DefaultDataSourceUpdateMode = DataSourceUpdateMode.Never;

        }


        #region Control Event

        void txtAttribute_TextChanged(object sender, TextChangedEventArgs e)
        {
            SetColor();
        }

        void btnAttribute_Click(object sender, RoutedEventArgs e)
        {

            if (!btnAttribute.IsEnabled)
                return;
            btnAttribute.IsEnabled = false;


            Envs.SetBusyIndicator(true);
            // _C_BPartner_ID = Envs.GetContext().GetContextAsInt(_windowNo, "C_BPartner_ID");

            int M_Product_ID = Envs.GetContext().GetContextAsInt(_windowNo, "M_Product_ID");


            //	M_Product.M_AttributeSetInstance_ID = 8418
            bool productWindow = _AD_Column_ID == 8418;		//	HARDCODED

            //	Exclude ability to enter ASI
            bool exclude = true;
            if (M_Product_ID != 0)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    VAdvantage.Model.MProduct product = VAdvantage.Model.MProduct.Get(Envs.GetContext(), M_Product_ID);
                    int M_AttributeSet_ID = product.GetM_AttributeSet_ID();
                    if (M_AttributeSet_ID != 0)
                    {
                        VAdvantage.Model.MAttributeSet mas = VAdvantage.Model.MAttributeSet.Get(Envs.GetContext(), M_AttributeSet_ID);
                        exclude = mas.ExcludeEntry(_AD_Column_ID, Envs.GetContext().IsSOTrx(_windowNo));
                    }
                    Dispatcher.BeginInvoke(() => ButtonClick(M_Product_ID, productWindow, exclude));
                });
            }
            else
            {
                ButtonClick(M_Product_ID, productWindow, exclude);
            }
        }


        private void ButtonClick(int M_Product_ID, bool productWindow, bool exclude)
        {

            Envs.SetBusyIndicator(false);


            object oldValue = GetValue();

            int M_ProductBOM_ID = Envs.GetContext().GetContextAsInt(_windowNo, "M_ProductBOM_ID");
            //********** Change **********
            int M_Locator_ID = Envs.GetContext().GetContextAsInt(_windowNo, "M_Locator_ID");

            int M_AttributeSetInstance_ID = (oldValue == null || oldValue == DBNull.Value) ? 0 : Convert.ToInt32(oldValue);

            log.Config("M_Product_ID=" + M_Product_ID + "/" + M_ProductBOM_ID
                + ",M_AttributeSetInstance_ID=" + M_AttributeSetInstance_ID
                + ", AD_Column_ID=" + _AD_Column_ID);


            bool changed = false;
            if (M_ProductBOM_ID != 0)	//	Use BOM Component
                M_Product_ID = M_ProductBOM_ID;
            //	
            if (!productWindow && (M_Product_ID == 0 || exclude))
            {
                changed = true;
                txtAttribute.Text = "";
                //m_text.setText(null);
                M_AttributeSetInstance_ID = 0;
                NotifyChanged(changed, M_AttributeSetInstance_ID, oldValue);
            }
            else
            {
                //Dialogs.VPAttributesDialog vad = new Dialogs.VPAttributesDialog(M_AttributeSetInstance_ID,
                //    M_Product_ID, _C_BPartner_ID,
                //     productWindow, _AD_Column_ID, _windowNo);
                Dialogs.VPAttributesDialog vad = new Dialogs.VPAttributesDialog(M_AttributeSetInstance_ID,
                    M_Product_ID, M_Locator_ID, _C_BPartner_ID,
                     productWindow, _AD_Column_ID, _windowNo);
                // vad.ShowDialog();

                vad.Closed += (sn, ev) =>
                {

                    if (vad.IsChanged())
                    {

                        txtAttribute.Text = vad.GetM_AttributeSetInstanceName();
                        //m_text.setText(vad.getM_AttributeSetInstanceName());
                        M_AttributeSetInstance_ID = vad.GetM_AttributeSetInstance_ID();
                        changed = true;

                        //ADD IN PAttibuteList SL 
                        Model.MLookupStore.PAttributeCache[M_AttributeSetInstance_ID] = vad.GetM_AttributeSetInstanceName();
                        //End



                    }
                    NotifyChanged(changed, M_AttributeSetInstance_ID, oldValue);
                };

                vad.Show();

            }


        }

        private void NotifyChanged(bool changed, int M_AttributeSetInstance_ID, object oldValue)
        {

            //	Set Value
            if (changed)
            {
                log.Finest("Changed M_AttributeSetInstance_ID=" + M_AttributeSetInstance_ID);

                _value = new Object();				//	force re-query display
                if (M_AttributeSetInstance_ID == 0)
                    SetValue(null);
                else
                {
                    _value = M_AttributeSetInstance_ID;
                    //   SetValue(M_AttributeSetInstance_ID);
                }
                if (!Utility.Util.IsEqual(oldValue, _value))
                {
                    if (EditingControlDataGridView != null)
                    {
                        SetValueInDataGridColumn(_value);
                        EditingControlDataGridView.RaiseCellValueChanged(this);
                        _field.SetValue(_value);
                        ((DataUtil.DataObject)EditingControlDataGridView.SelectedItem).SetFieldValue(_colName.ToUpper(), _value);
                    }

                    else
                    {

                        try
                        {
                            _focus = true;
                            if (VetoableChangeListener != null)
                            {
                                VetoableChangeListener(this, EventArgs.Empty);
                            }
                            _focus = false;
                            //fireVetoableChange("M_AttributeSetInstance_ID", new Object(), getValue());
                        }
                        catch (Exception pve)
                        {
                            log.Log(Level.SEVERE, "", pve);
                        }

                    }
                }
            }
            btnAttribute.IsEnabled = true;

        }

        #endregion


        #region IControl
        public event EventHandler VetoableChangeListener;


        public int GetDisplayType()
        {
            return _displayType;
        }

        public void SetDisplayType(int displayType)
        {
            _displayType = displayType;
        }

        public bool GetIsReadonly()
        {
            return _readOnly;
        }

        public void SetReadOnly(bool readOnly)
        {
            _readOnly = readOnly;
            this.txtAttribute.IsReadOnly = readOnly;
            btnAttribute.Visibility = readOnly ? System.Windows.Visibility.Collapsed : System.Windows.Visibility.Visible;
            SetBackGround(readOnly);
        }

        public GridField GetField()
        {
            return _field;
        }

        public void SetField(GridField mField)
        {
            if (mField != null)
            {
                _windowNo = mField.GetWindowNo();
                _AD_Column_ID = mField.GetAD_Column_ID();
            }
            _field = mField;
        }

        public string GetName()
        {
            return this._colName;
        }

        public void SetName(string name)
        {
            this._colName = name;
        }

        public string GetText()
        {
            return this.txtAttribute.Text;
        }

        public object GetValue()
        {
            return _value;
        }

        public void SetValue(object value)
        {
            if (value == null || NO_INSTANCE.Equals(value) || value == DBNull.Value)
            {
                txtAttribute.Text = "";
                _value = value;
                return;
            }

            //	The same
            if (value.Equals(_value))
                return;
            //	new value
            log.Fine("Value=" + value);
            _value = value;

            string desc = _mPAttribute.GetDisplayFromList(value);

            if (desc != null && (desc == "" || desc.StartsWith("{")))
            {
                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {
                    desc =  _mPAttribute.GetDisplay(value);
                    Dispatcher.BeginInvoke(()=>txtAttribute.Text = desc);
                });
            }
            else
            {
                txtAttribute.Text = desc;
            }
        }

        public bool GetIsMandatory()
        {
            return _mandatory;
        }

        public void SetIsMandatory(bool value)
        {
            _mandatory = value;
        }


        private SolidColorBrush backColorBrush = new SolidColorBrush();

        public void SetBackGround(bool value)
        {
            if (value)
            {
                backColorBrush.Color = DataBase.GlobalVariable.READONLY_TEXT_BACK_COLOR;
                this.txtAttribute.Background = backColorBrush;
            }
            else
            {
                backColorBrush.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                this.txtAttribute.Background = backColorBrush;
                SetColor();
            }

        }

        private void SetColor()
        {
            if (_mandatory)
            {
                if (this.Text == "")
                {
                    backColorBrush.Color = DataBase.GlobalVariable.MANDATORY_TEXT_BACK_COLOR;
                    this.txtAttribute.Background = backColorBrush;
                }
                else
                {
                    backColorBrush.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                    this.txtAttribute.Background = backColorBrush;
                    if (_field != null)
                        _field.SetError(false);
                }
            }
        }



        public string GetSelectedText()
        {
            return this.txtAttribute.SelectedText;
        }

        public bool IsDisabled()
        {
            return _readOnly;
        }

        public void SetDisabled(bool disabled)
        {
            SetReadOnly(disabled);
        }

        public int GetTabIndex()
        {
            return this.TabIndex;
        }

        public void SetTabindex(int tabindex)
        {
            this.TabIndex = tabindex;
        }

        public bool Multiline
        {
            get
            {
                return false;
            }
            set
            {
                //throw new NotImplementedException();
            }
        }

        public bool Visible
        {
            get
            {
                return this.Visibility == System.Windows.Visibility.Visible;
            }
            set
            {
                this.Visibility = value ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }
        }

        public bool Focused
        {
            get { return _focus; }
        }

        public string BindValue
        {
            set
            {
                binding = null;
                binding = new Binding(value);
                binding.Mode = BindingMode.OneWay;
                this.SetBinding(VPAttribute.TextValueProperty, binding);
            }
        }

        public void Dispose()
        {
            _field = null;
        }
        #endregion IControl



        public VDataGrid EditingControlDataGridView
        {
            get;
            set;
        }

        public void SetValueInDataGridColumn(object value)
        {
            SetValue(value);
        }
    }
}
